package com.kvn.druid;

import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor;
import com.alibaba.druid.stat.TableStat;
import com.alibaba.druid.stat.TableStat.Condition;
import com.alibaba.druid.stat.TableStat.Name;
import com.kvn.interceptor.TableNameModifier;

import java.util.List;
import java.util.Map;

public class DruidParse {

    public static void parse(String sql) {
        MySqlStatementParser parser = new MySqlStatementParser(sql);

        List<SQLStatement> statementList = parser.parseStatementList();
        for (SQLStatement statement : statementList) {
            System.out.println("原始sql:" + statement.toString());

            MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
            statement.accept(visitor);
            // 获取表名称
//			System.out.println("Tables : " + visitor.getCurrentTable());
            // 获取操作方法名称,依赖于表名称
            System.out.println("Manipulation : " + visitor.getTables());
            Map<Name, TableStat> tableMap = visitor.getTables();
            for(Name name : tableMap.keySet()){
                System.out.println(name.getName());
                name = new Name("123");
            }


            List<Condition> conditions = visitor.getConditions();
            for(int i=0;i<conditions.size();i++){
                Condition condition = conditions.get(i);
                System.out.println(i + ":" + conditions.get(i));
                System.out.println("column=" + condition.getColumn());
                System.out.println("value=" + condition.getValues());

            }
            TableNameModifier tnm = new TableNameModifier("account_trade","account_trade_1");
            TableNameModifier tnm2 = new TableNameModifier("account_info","account_info_1");
            statement.accept(tnm);
            statement.accept(tnm2);

            // 获取字段名称
            System.out.println("fields : " + visitor.getColumns());
            System.out.println("替换表名后的sql:" + statement.toString());
        }

    }

    public static void main(String[] args) {
//		String sql = "update account_trade set user_id = ?";

//        String sql = "select * from account_trade ,account_info  where account_trade.user_id = ? and account_trade.account_trade= 'aaa' and account_trade.trade_type = '01' and account_trade.account_no = account_info.account_no";
//         带别名的
        String sql = "select * from account_trade at ,account_info ai where at.account_no = ai.account_no and at.user_id = ? and at.account_trade= 'aaa' and at.trade_type = '01' ";
        parse(sql);
    }

}
